<template>
  <div class="tasks-container">
    <!-- 统计卡片 -->
    <div class="stats-wrapper">
      <el-row :gutter="8" class="stats-cards compact">
      <el-col :span="6">
        <el-card class="stat-card compact" :body-style="{ padding: '1px 8px', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'center' }">
          <div class="stat-content compact">
            <el-icon class="stat-icon compact"><List /></el-icon>
            <div>
              <div class="stat-number compact">{{ taskStats.queueTasks }}</div>
              <div class="stat-label compact">队列任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card compact" :body-style="{ padding: '1px 8px', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'center' }">
          <div class="stat-content compact">
            <el-icon class="stat-icon compact"><VideoPlay /></el-icon>
            <div>
              <div class="stat-number compact">{{ taskStats.runningTasks }}</div>
              <div class="stat-label compact">执行中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card compact" :body-style="{ padding: '1px 8px', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'center' }">
          <div class="stat-content compact">
            <el-icon class="stat-icon compact"><Clock /></el-icon>
            <div>
              <div class="stat-number compact">{{ taskStats.waitingTasks }}</div>
              <div class="stat-label compact">等待</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card compact" :body-style="{ padding: '0px 8px', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'center' }">
          <div class="stat-content compact">
            <el-icon class="stat-icon compact"><Cpu /></el-icon>
            <div>
              <div class="stat-number compact">{{ taskStats.remainingProcesses }}</div>
              <div class="stat-label compact">空闲进程</div>
            </div>
          </div>
        </el-card>
      </el-col>
      </el-row>
    </div>
    
    <div  style="margin-left: 10px;">
      <div class="header-tabs">
        <el-radio-group v-model="taskStatusFilter" @change="handleStatusFilter">
          <el-radio-button label="">全部任务</el-radio-button>
          <el-radio-button label="running">执行中</el-radio-button>
          <el-radio-button label="stopped">历史任务</el-radio-button>
        </el-radio-group>
        <div style="display: flex; gap: 12px; align-items: center;">
          <el-select
             v-model="taskTypeFilter"
             placeholder="任务类型"
             style="width: 120px; height: 36px; border-radius: 6px;"
             clearable
           >
             <el-option label="全部" value="" />
             <el-option label="录制" value="record" />
             <el-option label="转推" value="push" />
             <el-option label="转码" value="transcode" />
   
          
           </el-select>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索任务名称或直播名称"
            :prefix-icon="Search"
            style="width: 300px; height: 36px; border-radius: 6px;"
            clearable
            @clear="searchKeyword = ''"
          />
          <el-button
            type="primary"
            :icon="Refresh"
            @click="fetchTasks"
            style="height: 36px; border-radius: 6px; font-weight: 500; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); width: auto; min-width: 80px;"
          >
            刷新
          </el-button>
          <el-button
            type="primary"
            plain
            @click="batchStartTasks"
            :disabled="selectedTaskIds.length === 0"
            style="height: 36px; border-radius: 6px; font-weight: 500; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); width: auto; min-width: 80px;"
          >
            批量启动
          </el-button>
          <el-button
            type="warning"
            plain
            @click="batchStopTasks"
            :disabled="selectedTaskIds.length === 0"
            style="height: 36px; border-radius: 6px; font-weight: 500; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); width: auto; min-width: 80px;"
          >
            批量停止
          </el-button>
        </div>
      </div>
    </div>

    <!-- 任务列表 -->
    <el-card style="margin: 10px;">
      <el-empty v-if="!loading && tasks.length === 0" description="暂无任务数据" />
      
      <div v-else>
        <el-table
          v-loading="loading"
          :data="paginatedTasks"
          style="width: 100%"
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" min-width="30" />
          <el-table-column prop="name" label="任务名称" min-width="300" />
          <el-table-column label="任务类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getTaskTypeTag(row.task_type)" size="small">
                {{ getTaskTypeText(row.task_type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="关联流" width="180">
            <template #default="{ row }">
              <span>{{ row.stream_name || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <div @click="handleStatusClick(row)">
                <el-tag :type="getStatusType(row.status)" :style="{cursor: ['failed', 'error', 'pending'].includes(row.status) ? 'pointer' : 'default'}">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="执行进程" width="200">
            <template #default="{ row }">
              <div v-if="row.pid">
                <div>节点ID: 本地</div>
                <div>进程ID: {{ row.pid }}</div>
              </div>
              <div v-else>
                <el-tag size="small" type="info">未启动</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="任务情况" width="200">
            <template #default="{ row }">
              <div v-if="row.status === 'pending'">
                <div @click="showPendingInfo" style="cursor: pointer;">
                  <el-tag type="warning" size="small">
                    队列中 (点击查看详情)
                  </el-tag>
                </div>
              </div>
              <div v-else-if="row.status === 'failed' || row.status === 'error'">
                <div @click="handleStatusClick(row)" style="cursor: pointer;">
                  <el-tag type="danger" size="small">
                    失败 (点击查看详情)
                  </el-tag>
                </div>
              </div>
              <div v-else-if="row.task_type === 'record'">
                <div v-if="row.file_size > 0">
                  {{ formatFileSize(row.file_size) }}
                </div>
                <div v-else>
                  <el-tag size="small" type="info">准备中</el-tag>
                </div>
              </div>
              <div v-else-if="row.task_type === 'push'">
                <el-tag :type="row.status === 'running' ? 'success' : 'info'" size="small">
                  {{ row.status === 'running' ? '转推流正常' : '转推已停止' }}
                </el-tag>
              </div>
              <div v-else-if="row.task_type === 'transcode'">
                <el-tag :type="row.status === 'running' ? 'success' : 'info'" size="small">
                  {{ row.status === 'running' ? '转码进程中' : '转码已停止' }}
                </el-tag>
              </div>
              <div v-else-if="row.status === 'idle'">
                <el-tag size="small" type="info">
                  队列中有{{ taskStats.pending }}个任务
                </el-tag>
              </div>
              <div v-else>
                <el-tag size="small" type="info">-</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-cell">
                <el-button-group>
                  <el-tooltip content="编辑配置" placement="top">
                    <el-button
                      size="small"
                      type="primary"
                      circle
                      plain
                      @click="editTaskConfig(row)">
                      <el-icon><Edit /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip :content="row.status === 'running' ? '停止任务' : '启动任务'" placement="top">
                    <el-button
                      size="small"
                      :type="row.status === 'running' ? 'warning' : 'success'"
                      circle
                      plain
                      @click="toggleTask(row)">
                      <el-icon>
                        <VideoPause v-if="row.status === 'running'" />
                        <VideoPlay v-else />
                      </el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="删除任务" placement="top">
                    <el-button 
                      size="small" 
                      type="danger" 
                      circle
                      plain
                      @click="deleteTask(row)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-tooltip>
                </el-button-group>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            style="display: flex; justify-content: center;"
          />
        </div>
      </div>
    </el-card>

    <!-- 任务配置编辑对话框 -->
    <el-dialog
      v-model="configDialogVisible"
      :title="`修改任务配置`"
      width="520px"
      destroy-on-close
      class="task-config-dialog compact ultra-compact"
    >
      <div class="task-config-container ultra-compact">
        <el-form
          v-if="currentTask"
          ref="configFormRef"
          :model="configForm"
          label-width="100px"
          label-position="right"
          class="task-form ultra-compact"
          size="small"
        >
        <!-- 基本信息 -->
        <el-form-item label="任务名称" required class="compact-item">
          <el-input
            v-model="currentTask.name"
            placeholder="请输入任务名称"
            :rules="[{ required: true, message: '任务名称不能为空' }]"
            size="small"
          />
        </el-form-item>
        <el-form-item label="任务类型" class="compact-item">
          <el-tag :type="getTaskTypeTag(currentTask.task_type)">
            {{ getTaskTypeText(currentTask.task_type) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="关联流" class="compact-item">
          <el-input v-model="currentTask.stream_name" disabled size="small" />
        </el-form-item>

        <!-- 录制任务配置（只读） -->
        <template v-if="currentTask.task_type.includes('record')">
          <div class="task-section ultra-compact">
            <div class="section-header ultra-compact">
              <i class="section-icon ultra-compact">🎬</i>
              <span>录制任务</span>
            </div>
            <el-form-item label="录制格式" class="compact-item">
              <el-input v-model="configForm.record_format" disabled size="small" />
            </el-form-item>
            <el-form-item label="文件路径" class="compact-item">
              <el-input v-model="configForm.record_path" disabled size="small" />
            </el-form-item>
          </div>
        </template>

        <!-- 转推任务配置（可编辑） -->
        <template v-if="currentTask.task_type.includes('push')">
          <div class="task-section ultra-compact">
            <div class="section-header ultra-compact">
              <i class="section-icon ultra-compact">🔄</i>
              <span>转推任务</span>
            </div>
            <el-form-item label="转推地址" required class="compact-item">
              <el-input
                v-model="configForm.push_url"
                placeholder="请输入转推地址"
                :rules="[{ required: true, message: '转推地址不能为空' }]"
                size="small"
              />
            </el-form-item>
          </div>
        </template>

        <!-- 转码任务配置（只读） -->
        <template v-if="currentTask.task_type.includes('transcode')">
          <div class="task-section ultra-compact">
            <div class="section-header ultra-compact">
              <i class="section-icon ultra-compact">⚙️</i>
              <span>转码任务</span>
            </div>
            <el-form-item label="转码模板" class="compact-item">
              <el-input v-model="configForm.transcode_template_name" disabled size="small" />
            </el-form-item>
            <el-form-item label="输出地址" class="compact-item">
              <el-input v-model="configForm.output_path" disabled size="small" />
            </el-form-item>
          </div>
        </template>

        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer ultra-compact">
          <el-button @click="configDialogVisible = false" size="small">取消</el-button>
          <el-button type="primary" @click="saveTaskConfig" size="small">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 错误详情对话框 -->
    <el-dialog
      v-model="errorDialogVisible"
      title="任务失败详情"
      class="error-detail-dialog auto-size-message-box"
      destroy-on-close
      width="95%"
    >
      <div v-if="currentErrorTask" class="error-content">
        <div class="error-header">
          <h4>任务信息</h4>
          <p>任务名称：{{ currentErrorTask.name }}</p>
          <p>任务类型：{{ getTaskTypeText(currentErrorTask.task_type) }}</p>
          <p>状态：{{ getStatusText(currentErrorTask.status) }}</p>
          <p v-if="currentErrorTask.stream_name">关联流：{{ currentErrorTask.stream_name }}</p>
        </div>
        <div class="error-message-section">
          <h4>错误信息</h4>
          <pre class="error-message">{{ currentErrorTask.error_message || '暂无详细错误信息' }}</pre>
        </div>
      </div>
      <div v-else>加载中...</div>
      <template #footer>
        <el-button @click="errorDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 队列状态对话框 -->
    <el-dialog
      v-model="queueDialogVisible"
      title="队列状态"
      class="queue-status-dialog auto-size-message-box"
      destroy-on-close
      width="50%"
    >
      <div class="queue-info">
        <p>已加入队列，当前队列中有 <strong>{{ taskStats.pending }}</strong> 个任务等待中</p>
        <p>系统将按照任务创建时间顺序自动处理</p>
      </div>
      <template #footer>
        <el-button @click="queueDialogVisible = false">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoPause, VideoPlay, Delete, Refresh, Search, Edit, List, Clock, Cpu } from '@element-plus/icons-vue'
import api from '@/api'

// 数据
const tasks = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const transcodeTemplates = ref([])
const selectedTaskIds = ref([])

// 任务配置编辑
const configDialogVisible = ref(false)
const currentTask = ref(null)
const configForm = ref({})
const configFormRef = ref()

// 筛选
const taskStatusFilter = ref('')
const taskTypeFilter = ref('')
const searchKeyword = ref('')

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString('zh-CN')
}

// 任务统计信息
// 简化版taskStats，等待后端接口提供数据
const taskStats = {
  queueTasks: 10,
  runningTasks: 4,
  waitingTasks: 6,
  remainingProcesses: 0
}

const filteredTasks = computed(() => {
  let result = tasks.value || []
  
  // 状态筛选
  if (taskStatusFilter.value === 'running') {
    result = result.filter(task => task.status === 'running')
  } else if (taskStatusFilter.value === 'stopped') {
    result = result.filter(task => task.status === 'stopped' || task.status === 'completed' || task.status === 'failed')
  }
  
  // 任务类型筛选
    if (taskTypeFilter.value) {
      result = result.filter(task => task.task_type === taskTypeFilter.value)
    }
  
  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(task => 
      task.name.toLowerCase().includes(keyword) ||
      task.stream_name?.toLowerCase().includes(keyword)
    )
  }
  
  return result
})

const paginatedTasks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTasks.value.slice(start, end)
})

// 模拟数据 - 提供完整的任务数据以便展示统计卡片
const loadMockData = () => {
  tasks.value = [
    // 运行中任务（4个）
    {
      id: 1,
      name: '直播录制任务1',
      task_type: 'record',
      stream_name: '测试直播流1',
      status: 'running',
      config: {
        encode_preset: '高清',
        encode: {
          width: 1920,
          height: 1080
        }
      },
      created_at: '2024-01-15 10:30:00'
    },
    {
      id: 2,
      name: '直播转码任务1',
      task_type: 'transcode',
      stream_name: '测试直播流2',
      status: 'running',
      config: {
        encode_preset: '高清',
        encode: {
          width: 1280,
          height: 720
        }
      },
      created_at: '2024-01-15 11:00:00'
    },
    {
      id: 3,
      name: '直播转推任务1',
      task_type: 'push',
      stream_name: '测试直播流3',
      status: 'running',
      config: {
        encode_preset: '标清',
        encode: {
          width: 720,
          height: 480
        }
      },
      created_at: '2024-01-15 12:15:00'
    },
    {
      id: 4,
      name: '直播拆条任务1',
      task_type: 'clip',
      stream_name: '测试直播流4',
      status: 'running',
      config: {
        encode_preset: '标清',
        encode: {
          width: 720,
          height: 480
        }
      },
      created_at: '2024-01-15 13:00:00'
    },
    // 等待中任务（6个）
    {
      id: 5,
      name: '直播录制任务2',
      task_type: 'record',
      stream_name: '测试直播流5',
      status: 'pending',
      config: {
        encode_preset: '高清',
        encode: {
          width: 1920,
          height: 1080
        }
      },
      created_at: '2024-01-15 14:30:00'
    },
    {
      id: 6,
      name: '直播转码任务2',
      task_type: 'transcode',
      stream_name: '测试直播流6',
      status: 'pending',
      config: {
        encode_preset: '超清',
        encode: {
          width: 1920,
          height: 1080
        }
      },
      created_at: '2024-01-15 15:00:00'
    },
    {
      id: 7,
      name: '直播转推任务2',
      task_type: 'push',
      stream_name: '测试直播流7',
      status: 'pending',
      config: {
        encode_preset: '标清',
        encode: {
          width: 720,
          height: 480
        }
      },
      created_at: '2024-01-15 15:30:00'
    },
    {
      id: 8,
      name: '直播拆条任务2',
      task_type: 'clip',
      stream_name: '测试直播流8',
      status: 'pending',
      config: {
        encode_preset: '高清',
        encode: {
          width: 1280,
          height: 720
        }
      },
      created_at: '2024-01-15 16:00:00'
    },
    {
      id: 9,
      name: '复合任务1',
      task_type: 'record_transcode',
      stream_name: '测试直播流9',
      status: 'pending',
      config: {
        encode_preset: '高清',
        encode: {
          width: 1280,
          height: 720
        }
      },
      created_at: '2024-01-15 16:30:00'
    },
    {
      id: 10,
      name: '复合任务2',
      task_type: 'transcode_push',
      stream_name: '测试直播流10',
      status: 'pending',
      config: {
        encode_preset: '超清',
        encode: {
          width: 1920,
          height: 1080
        }
      },
      created_at: '2024-01-15 17:00:00'
    },
    // 已停止任务（额外添加，不影响统计数字）
    {
      id: 11,
      name: '历史录制任务',
      task_type: 'record',
      stream_name: '历史直播流',
      status: 'stopped',
      config: {
        encode_preset: '标清',
        encode: {
          width: 1280,
          height: 720
        }
      },
      created_at: '2024-01-14 09:15:00'
    },
    {
      id: 12,
      name: '已完成任务',
      task_type: 'transcode',
      stream_name: '历史直播流2',
      status: 'completed',
      config: {
        encode_preset: '高清',
        encode: {
          width: 1920,
          height: 1080
        }
      },
      created_at: '2024-01-13 14:00:00'
    }
  ]
}

// 获取数据
const fetchTasks = async () => {
  loading.value = true
  try {
    const res = await api.get('/tasks/list', {
      params: {
        status: taskStatusFilter.value,
        task_type: taskTypeFilter.value,
        page: currentPage.value,
        limit: pageSize.value
      }
    })
    
    // 响应数据已经是处理后的data字段
    if (res && Array.isArray(res.items)) {
      tasks.value = res.items
      total.value = res.total || res.items.length
    } else {
      console.error('API返回格式错误:', res)
      tasks.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    tasks.value = []
    total.value = 0
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

const fetchTranscodeTemplates = async () => {
  try {
    const res = await api.get('/transcode-templates/list')
    if (res && Array.isArray(res.items)) {
      transcodeTemplates.value = res.items
    } else {
      transcodeTemplates.value = []
    }
  } catch (error) {
    console.error('获取转码模板失败:', error)
    transcodeTemplates.value = []
  }
}

const handleStatusFilter = () => {
  // 筛选变化时自动更新列表
}

// 任务操作
const toggleTask = async (task) => {
  if (task.status === 'running') {
    await stopTask(task)
  } else {
    await startTask(task)
  }
}

const startTask = async (task) => {
  try {
    await api.post(`/tasks/${task.id}/start`)
    ElMessage.success('任务启动成功')
    fetchTasks()
  } catch (error) {
    ElMessage.error('启动任务失败')
  }
}

const stopTask = async (task) => {
  try {
    await api.post(`/tasks/${task.id}/stop`)
    ElMessage.success('任务停止成功')
    fetchTasks()
  } catch (error) {
    ElMessage.error('停止任务失败')
  }
}

const deleteTask = async (task) => {
  try {
    await ElMessageBox.confirm('确定要删除这个任务吗？', '确认删除')
    await api.delete(`/tasks/${task.id}`)
    ElMessage.success('删除成功')
    fetchTasks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除任务失败')
    }
  }
}

// 批量操作
const handleSelectionChange = (selection) => {
  selectedTaskIds.value = selection.map(task => task.id)
}

const batchStartTasks = async () => {
  try {
    const selectedTasks = tasks.value.filter(task => 
      selectedTaskIds.value.includes(task.id) && task.status !== 'running'
    )
    
    if (selectedTasks.length === 0) {
      ElMessage.warning('请选择非运行中的任务')
      return
    }
    
    await ElMessageBox.confirm(`确定要批量启动 ${selectedTasks.length} 个任务吗？`, '确认批量启动')
    
    const promises = selectedTasks.map(task => api.post(`/tasks/${task.id}/start`))
    await Promise.all(promises)
    
    ElMessage.success(`成功启动 ${selectedTasks.length} 个任务`)
    fetchTasks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量启动任务失败')
    }
  }
}

const batchStopTasks = async () => {
  try {
    const selectedTasks = tasks.value.filter(task => 
      selectedTaskIds.value.includes(task.id) && task.status === 'running'
    )
    
    if (selectedTasks.length === 0) {
      ElMessage.warning('请选择运行中的任务')
      return
    }
    
    await ElMessageBox.confirm(`确定要批量停止 ${selectedTasks.length} 个任务吗？`, '确认批量停止')
    
    const promises = selectedTasks.map(task => api.post(`/tasks/${task.id}/stop`))
    await Promise.all(promises)
    
    ElMessage.success(`成功停止 ${selectedTasks.length} 个任务`)
    fetchTasks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量停止任务失败')
    }
  }
}



// 任务状态点击处理函数
const handleStatusClick = (task) => {
  if (task.status === 'failed' || task.status === 'error') {
    // 使用对话框显示失败信息，更适合大量内容
    errorDialogVisible.value = true
    currentErrorTask.value = task
  } else if (task.status === 'pending') {
    showPendingInfo()
  }
}

// 显示等待中任务信息
const showPendingInfo = () => {
  queueDialogVisible.value = true
}

// 工具函数
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getTaskTypeTag = (type) => {
  // 组合任务类型使用特殊颜色
  if (type.includes('_')) {
    return 'danger'  // 红色表示复合任务
  }
  const map = {
    record: 'warning',
    push: 'success',
    transcode: 'primary',
    clip: 'info'
  }
  return map[type] || 'info'
}

const getTaskTypeText = (type) => {
  // 解析组合任务类型
  if (type.includes('_')) {
    const types = type.split('_')
    const typeMap = {
      record: '录制',
      push: '转推',
      transcode: '转码',
      clip: '拆条'
    }
    return types.map(t => typeMap[t] || t).join(' + ')
  }
  
  const map = {
    record: '录制',
    push: '转推',
    transcode: '转码',
    clip: '拆条'
  }
  return map[type] || type
}

const getStatusType = (status) => {
  const map = {
    running: 'success',
    stopped: 'info',
    error: 'danger',
    pending: 'warning'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    running: '运行中',
    stopped: '已停止',
    completed: '已完成',
    failed: '失败',
    error: '错误',
    pending: '等待中'
  }
  return map[status] || status
}

// 生命周期
onMounted(() => {
  fetchTasks()
  fetchTranscodeTemplates()
})

// 分页处理方法
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchTasks()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTasks()
}

// 错误详情对话框状态
const errorDialogVisible = ref(false)
const currentErrorTask = ref(null)

// 队列状态对话框状态
const queueDialogVisible = ref(false)

// 任务配置编辑方法
const editTaskConfig = (task) => {
  currentTask.value = { ...task }
  
  // 根据任务类型初始化配置表单
  const config = task.config || {}
  configForm.value = {
    // 优先从task.config获取，其次从task对象直接获取，确保转推地址能正确显示
    push_url: config.push_url || task.push_url || '',
    record_format: 'ts', // 录制格式固定为ts
    record_path: '/data/recordings', // 录制路径固定
    // 转码任务相关信息（只读）
    transcode_template_name: '',
    output_path: config.output_path || ''
  }
  
  // 如果是转码任务，查找并设置转码模板名称
  if (task.task_type.includes('transcode') && config.transcode_template) {
    const template = transcodeTemplates.value.find(t => t.id === config.transcode_template)
    configForm.value.transcode_template_name = template ? template.name : config.transcode_template
  }
  
  configDialogVisible.value = true
}

const saveTaskConfig = async () => {
  if (!configFormRef.value) return
  
  try {
    await configFormRef.value.validate()
    
    const updateData = {
      id: currentTask.value.id,
      name: currentTask.value.name // 保持任务名称不变
    }
    
    // 根据任务类型添加对应的配置
    if (currentTask.value.task_type.includes('push')) {
      updateData.config = {
        ...currentTask.value.config,
        push_url: configForm.value.push_url
      }
      // 同时更新task对象中的push_url，确保数据一致性
      updateData.push_url = configForm.value.push_url
    }
    // 转码任务配置为只读，不需要更新
    
    await api.put(`/tasks/${currentTask.value.id}`, updateData)
    ElMessage.success('任务配置更新成功')
    configDialogVisible.value = false
    fetchTasks() // 重新加载任务列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('更新任务配置失败')
    }
  }
}

// 监听筛选变化时重置到第一页
watch([taskStatusFilter, taskTypeFilter, searchKeyword], () => {
  currentPage.value = 1
  fetchTasks()
})
</script>

<style scoped>
/* 自定义表格样式 */
.el-table th {
  background-color: #f8f9fa;
}

/* 自动调整弹窗大小样式 */
:deep(.auto-size-message-box) {
  max-width: 75vw !important;
  max-height: 75vh !important;
}

/* 错误详情对话框样式 */
:deep(.error-detail-dialog .el-dialog__body) {
  max-height: 60vh !important;
  overflow-y: auto;
  padding: 20px;
}

:deep(.error-content) {
  line-height: 1.6;
}

:deep(.error-header) {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
}

:deep(.error-message-section) {
  margin-top: 15px;
}

:deep(.error-message) {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 40vh;
  overflow-y: auto;
  border: 1px solid #e8e8e8;
}

/* 任务配置对话框样式调整 */
:deep(.task-config-dialog) {
  max-width: 75vw !important;
  max-height: 75vh !important;
}

:deep(.task-config-dialog .el-dialog__body) {
  max-height: 60vh !important;
  overflow-y: auto;
}

.el-table__empty-block {
  min-height: 300px;
}

/* 任务状态标签样式 */
.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;
}

/* 任务类型标签样式 */
.type-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 操作按钮组样式 */
.action-buttons {
  display: flex;
  gap: 8px;
}

/* 批量操作按钮样式 */
.batch-actions {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

/* 头部标签样式 */
.header-tabs {
  display: flex;
  gap: 20px;
  align-items: center;
}

/* 统计卡片样式 - 优化边距和间距 */
.stats-wrapper {
  margin: 10px;
  padding: 2px;
}

.stats-cards {
  margin: 0;
  padding: 0;
}

.stat-card {
  height: 50px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  border: 1px solid #e8e8e8;
  padding: 3px;
}

.stat-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.stat-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  height: 100%;
}

.stat-icon {
  font-size: 20px;
  flex-shrink: 0;
  color: #409eff;
}

.stat-number {
  font-size: 16px;
  font-weight: 600;
  line-height: 1.2;
  color: #333;
}

.stat-label {
  font-size: 12px;
  line-height: 1.2;
  color: #666;
}

/* 任务配置对话框样式 - 参考TaskConfigDialog组件 */
.task-config-dialog.compact.ultra-compact {
  --el-dialog-border-radius: 6px;
}

.task-config-container.ultra-compact {
  padding: 2px 0;
}

.task-form.ultra-compact {
  margin: 0;
}

.task-section.ultra-compact {
  margin-bottom: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.section-header.ultra-compact {
  margin-bottom: 8px;
  padding-bottom: 4px;
}

.section-icon.ultra-compact {
  font-size: 14px;
  margin-right: 4px;
}

.section-header.ultra-compact span {
  font-size: 15px;
  font-weight: 600;
}

:deep(.ultra-compact .el-form-item) {
  margin-bottom: 8px;
}

:deep(.ultra-compact .el-form-item__label) {
  font-size: 13px;
  font-weight: 500;
  padding-right: 6px;
}

:deep(.compact-item) {
  margin-bottom: 6px !important;
}

:deep(.ultra-compact .readonly-input .el-input__wrapper) {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 3px 8px;
}

:deep(.ultra-compact .readonly-input .el-input__inner) {
  font-size: 13px;
  line-height: 1.4;
}

:deep(.ultra-compact .el-dialog__body) {
  padding: 10px 14px;
}

:deep(.ultra-compact .el-dialog__header) {
  padding: 10px 14px;
}

:deep(.ultra-compact .el-dialog__title) {
  font-size: 15px;
}

:deep(.ultra-compact .el-dialog__close) {
  font-size: 14px;
}

:deep(.ultra-compact .el-button--small) {
  padding: 5px 10px;
  font-size: 13px;
}

.dialog-footer.ultra-compact {
  gap: 6px;
}

@media (max-width: 768px) {
  .task-config-dialog.compact.ultra-compact {
    width: 98vw !important;
  }
  
  .task-section.ultra-compact {
    padding: 8px 10px;
    margin-bottom: 8px;
  }
  
  :deep(.ultra-compact .el-form-item__label) {
    font-size: 13px;
  }
}

/* 自动调整对话框大小样式 */
.auto-size-message-box {
  max-width: 95vw;
  max-height: 95vh;
  display: flex;
  flex-direction: column;
}

.auto-size-message-box :deep(.el-dialog__body) {
  flex: 1;
  min-height: 200px;
  overflow-y: auto;
}

/* 错误详情对话框特定样式 */
.error-detail-dialog :deep(.el-dialog__body) {
  padding: 16px 20px;
  max-height: 80vh;
  overflow-y: auto;
}

.error-detail-dialog .error-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.error-detail-dialog .error-header {
  background: #f8f9fa;
  padding: 12px 16px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.error-detail-dialog .error-header h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.error-detail-dialog .error-header p {
  margin: 4px 0;
  color: #606266;
  font-size: 14px;
}

.error-detail-dialog .error-message-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.error-detail-dialog .error-message {
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 6px;
  padding: 12px 16px;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 40vh;
  overflow-y: auto;
}

/* 队列状态对话框样式 */
.queue-status-dialog :deep(.el-dialog__body) {
  padding: 16px 20px;
}

.queue-status-dialog .queue-info {
  text-align: center;
  color: #606266;
  font-size: 14px;
  line-height: 1.8;
}
</style>